<script lang="ts" setup>
import {reactive, ref} from "vue";
import {onHide, onLoad, onPullDownRefresh, onReachBottom, onShow} from "@dcloudio/uni-app";
import MsgDetailList from "@/subPkg/message/components/MsgDetailList.vue";
import {clearUnreadApi, getUserChatListApi} from "@/api/chat";
import type {ChatPreListItem} from "@/interface/Chat";
import {useUserStore} from "@/stores/user";

const {safeAreaInsets} = uni.getSystemInfoSync()

// 消息列表项
interface MsgMenuItem {
  title: string,
  type?: 0 | 1 | 2
  icon: string,
  badge: number
}

uni.$on('updateChatList', (msg: pushMessage) => {
  const senderId = msg.senderId
  const newIndex = chatMsgList.value.findIndex(item => item.userId === senderId)
  chatMsgList.value[newIndex].unreadNum += msg.increaseCount!
  chatMsgList.value[newIndex].lastMessage = msg.content
  chatMsgList.value[newIndex].lastTime = msg.createTime
})
onShow(async () => {
  await getUserChatList()
})
onHide(() => {
  isNoMore.value = false
  page.value = 1
})
onLoad((option) => {
  msgMenuList[0].badge = option?.newLikedCount
  msgMenuList[1].badge = option?.newReplyCount
  msgMenuList[2].badge = option?.newSystemCount
})
const msgMenuList = reactive<MsgMenuItem[]>([
  {
    title: '收到的赞',
    icon: '/static/msg-like.png',
    badge: 0,
    type: 0
  },
  {
    title: '回复我的',
    icon: '/static/msg-reply.png',
    badge: 0,
    type: 1
  },
  {
    title: '系统通知',
    icon: '/static/msg-system.png',
    badge: 0,
    type: 2
  },
  // {
  //   title: '回复我的',
  //   icon: ''
  // }
])

const handleMessage = (item: MsgMenuItem) => {
  switch (item.type) {
    case  0:
      msgMenuList[0].badge = 0;
      break
    case 1:
      msgMenuList[1].badge = 0;
      break
    case 2:
      msgMenuList[2].badge = 0;
      break
  }
  uni.navigateTo({
    url: '/subPkg/message/messageList/messageList?title=' + item.title + '&type=' + item.type
  })
}
const chatMsgList = ref<ChatPreListItem[]>([])
const loading = ref(false)
const chatDelay = ref(false)
const page = ref(1)
const pageSize = 10
const isNoMore = ref(false)
/**
 * 获取用户历史消息
 */
const getUserChatList = async () => {
  // TODO 获取本地存储数据
  // 本地数据不存在，重新获取用户的历史聊天列表
  if (chatDelay.value || isNoMore.value) {
    return
  }
  chatDelay.value = true
  const res = await getUserChatListApi(page.value, pageSize)
  chatDelay.value = false
  chatMsgList.value = res.data.data
  if (page.value * pageSize >= res.data.total) {
    isNoMore.value = true
  }
}
onReachBottom(() => {
  if (chatDelay.value || isNoMore.value) {
    return
  }
  page.value++
  getUserChatList()
})
onPullDownRefresh(async () => {
  isNoMore.value = false
  if (chatDelay.value) {
    return
  }
  page.value = 1
  const tempChatList = chatMsgList.value
  try {
    chatMsgList.value = []
    await getUserChatList()
  } catch (e) {
    chatMsgList.value = tempChatList
    uni.stopPullDownRefresh()
  }
  uni.stopPullDownRefresh()
})

const showActions = () => {
  uni.showActionSheet({
    itemList: ['全部标为已读'],
    itemColor: '#39c5bb',
    success: (res) => {
      if (res.tapIndex === 0) {
        popupClear.value.open()
      }
    },
    fail: (res) => {
      console.log(res.errMsg)
    }
  })
}

const userStore = useUserStore();
const popupClear = ref()
const clearUnread = async () => {
  await clearUnreadApi()
  // 清除成功后，重新获取用户的历史聊天列表
  chatMsgList.value.forEach((item) => {
    item.unreadNum = 0
  })
  msgMenuList.forEach((item, index) => {
    item.badge = 0
  })
}
</script>

<template>
  <view :scroll-y="true" :style="{paddingBottom:'60px',height:'100vh',paddingTop:safeAreaInsets?.top+50+'px'}">
    <view style="position:fixed;top: 0;left: 0;right: 0;z-index: 999;">
      <aw-nav-second title="消息中心">
        <template v-slot:nav-right>
          <text class="cuIcon-moreandroid flex justify-end align-center text-gray"
                style="flex: 1;font-size: 23px" @click="showActions"></text>
        </template>
      </aw-nav-second>
    </view>
    <view class="msg-menu">
      <view v-for="(item,index) in msgMenuList" class="msg-menu-item" hover-class="msg-hover">
        <view class="cu-avatar" @click="handleMessage(item)">
          <view v-show="item.badge>0" class="cu-tag badge">{{ item.badge }}</view>
          <image :src="item.icon" mode="aspectFit" style="width: 60rpx;height: 60rpx"></image>
        </view>
        <text class="text-gray text-sm">{{ item.title }}</text>
      </view>
    </view>
    <view class="msg-list">
      <view class="msg-title text-black text-df">消息列表</view>
      <view v-for="item in chatMsgList" :key="item.listId" style="width: 100%">
        <MsgDetailList :msg-item=item></MsgDetailList>
      </view>
    </view>
    <view v-if="isNoMore" class="flex justify-center text-gray text-sm padding-sm" style="width: 100%">没有更多了哟~
    </view>
  </view>
  <uni-popup ref="popupClear" type="dialog">
    <uni-popup-dialog confirm-text="确认" content="是否确认全部标为已读？" title="提示" type="info"
                      @confirm="clearUnread"></uni-popup-dialog>
  </uni-popup>
</template>
<style lang="scss" scoped>
/* #ifdef H5 */
body {
  background-color: #f1f1f1;
}

/* #endif */
.msg-menu {
  width: 100%;
  height: 200rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 40rpx 20rpx 10rpx 20rpx;
  border-bottom: #e6e6e6 1px solid;
  background-color: #fff;
  transition: all .2s ease-in-out;

  &-item {
    width: 150rpx;
    height: 150rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 20rpx;
  }
}

.msg-list {
  margin-top: 20rpx;
  background-color: #fff;
  width: 100%;
}

.msg-title {
  width: 100%;
  border-bottom: #e6e6e6 1px solid;
  padding: 20rpx 0 20rpx 25rpx;
}


.msg-hover {
  transition: all .2s ease-in-out;
  background-color: #f2f2f2;
  border-radius: 10rpx;
  box-shadow: 0 0 10rpx #f1f1f1;
}
</style>
